import {
	app,
	BrowserWindow,
	Menu,
	Tray,
	shell,
	globalShortcut
} from "electron"
import path, { join } from "path"

// eslint-disable-next-line @typescript-eslint/no-var-requires
const electronLocalshortcut = require('electron-localshortcut')

export const windowsCfg = {
	id: "", // only id
	title: "", // Window title
	width: "", // Width
	height: "", // Height
	minWidth: "", // Minimum width
	minHeight: "", // Minimum height
	route: "", // Page routing URL '/manage?id=123'
	resizable: true, // Whether it supports window resizing
	maximize: false, // Whether to maximize
	backgroundColor: "#eee", // Window background color
	data: null, // data
	isFocus: false,
	isAlwaysOnTop: false,
	isMultiWindow: false, // Whether multiple windows are supported ( If false, When the form exists , Creating again doesn't create a new form only focus Show it ,, If true, Even if the form exists , You can also create a new )
	isMainWin: false, // Whether or not the main window ( When it comes to true Will replace the current main window )
	parentId: "", // The parent window id Create a parent-child window -- The child window always appears at the top of the parent window 【 The parent window can operate 】
	modal: false, // Modal window -- Modal windows are child windows that disable the parent window , To create a modal window, you must set parent and modal Options 【 The parent window cannot operate 】
}

type IVueElectronBrowserWindow = Partial<BrowserWindow> & {
	route: string
	isMultiWindow: boolean
	isMainWin: boolean
}
export default class ElecWindows {
	main: BrowserWindow | null = null // 主窗口
	group: { [key: string]: IVueElectronBrowserWindow } = {} // 窗口集合
	tray: Tray | null = null // 系统托盘

	winOpts(wh: [number, number] = [800, 600]) {
		return {
			width: wh[0],
			height: wh[1],
			backgroundColor: "#f00",
			minimizable: true,
			maximizable: true,
			show: false,
			webPreferences: {
				preload: join(__dirname, "../preload/index.js"),
				nodeIntegration: true,
				contextIsolation: false
			},
		} as any
	}

	getWindow(id: number | string) {
		return BrowserWindow.fromId(+id)
	}

	getAllWindows() {
		return BrowserWindow.getAllWindows()
	}

	createWindow(options: any) {
		const args = Object.assign({}, windowsCfg, options)
		for (const i in this.group) {
			if (
				this.getWindow(i) &&
				this.group[i].route === args.route &&
				!this.group[i].isMultiWindow
			) {
				const win = this.getWindow(i)
				win?.focus()
				return win
			}
		}
		const opt = this.winOpts([args.width || 540, args.height || 990])
		
		if (args.parentId) {
			console.log("current parent_id: " + args.parentId)
			opt.parent = this.getWindow(args.parentId)
		}
		if (typeof args.modal === "boolean") opt.modal = args.modal
		if (typeof args.resizable === "boolean") opt.resizable = args.resizable
		if (args.backgroundColor) opt.backgroundColor = args.backgroundColor
		if (args.minWidth) opt.minWidth = args.minWidth
		if (args.minHeight) opt.minHeight = args.minHeight
		if (args.title) opt.title = args.title || ""
		const win = new BrowserWindow(opt)
		// 视图宽高比
		win.setAspectRatio(opt.width/opt.height)
		console.log("current window_id: " + win.id)
		this.group[win.id] = {
			route: args.route,
			isMultiWindow: args.isMultiWindow,
			isMainWin: args.isMainWin,
		}
		console.log('windows group:', this.group)
		if (args.maximize && args.resizable) {
			win.maximize()
		}
		if (args.isAlwaysOnTop) {
			win.setAlwaysOnTop(true)
		}
		if (args.isfocus) {
			win.focus()
		}
		if (args.isMainWin) {
			if (this.main) {
				delete this.group[this.main.id]
				this.main?.close()
			}
			this.main = win
		}
		args.id = win.id
		if (!app.isPackaged) {
			win.loadURL(`http://localhost:${process.env.VITE_DEV_SERVER_PORT}`)
			win.webContents.openDevTools()
		} else {
			win.loadFile(join(__dirname, `../../index.html`))
		}
		electronLocalshortcut.register(win, 'Ctrl+Shift+i', () => {
			win.webContents.openDevTools()
		})

		win.webContents.session.webRequest.onHeadersReceived((details: any, callback: any) => {
			callback({ responseHeaders: Object.fromEntries(Object.entries(details.responseHeaders).filter(header => !/x-frame-options|content-security-policy/i.test(header[0]))) });
		})
		
		// 去除默认菜单
		Menu.setApplicationMenu(null)

		// group对象删除对应窗口数据
		win.on("closed", () => {
			// 主窗口关闭在主进程中单独做了拦截
			if (!args.isMainWin) {
				this.closeWindow(args.id)
			}
		})

		// 优雅的展示窗口
		win.once("ready-to-show", () => {
			win.show()
		})

		// 只允许打开可信内容
		win.webContents.setWindowOpenHandler(({ url }) => {
			if (url.startsWith("https:")) shell.openExternal(url)
			return { action: "deny" }
		})

		return win
	}

	closeAllWindow() {
		for (const i in this.group) {
			this.closeWindow(i)
		}
	}

	closeWindow(id: string) {
		if (this.group[id]) {
			if (this.getWindow(id)) {
				this.getWindow(id)?.close()
			}
			delete this.group[id]
			console.log('windows group:', this.group)
		}
	}

	openAllWindow() {
		for (const i in this.group) {
			if (this.group[i]) {
				const win = this.getWindow(i)
				if (!win) return
				if (win.isMinimized()) win.restore()
				win.setSkipTaskbar(false)
				win.show()
			}
		}
	}

	closeOtherWindow() {
		for (const i in this.group) {
			if (this.group[i].isMainWin) {
				continue
			}
			this.closeWindow(i)
		}
	}

	createTray() {
		const contextMenu = Menu.buildFromTemplate([
			{
				label: "打开应用",
				click: () => {
					this.openAllWindow()
				},
			},
			{
				label: "退出应用",
				click: () => {
					app.quit()
				},
			},
		])
		const trayIco = path.join(__dirname, "../main/tray-icon.png")
		this.tray = new Tray(trayIco)
		this.tray.setContextMenu(contextMenu)
		this.tray.setToolTip('vue3-electron-template')
		this.tray.on('click', () => {
			this.openAllWindow()
		})
		console.log("System tray created successfully")
	}
}
